// 为了便于维护 这个超级大项目 路由守卫抽离出来
import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 导入进度条三方库
import 'nprogress/nprogress.css' // 导入进度条样式
import { getToken } from '@/utils/auth' // 导入获取token的方法
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // 白名单

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start() // 开始进度条

  // set page title
  document.title = getPageTitle(to.meta.title) // 设置页面标题

  // 判断用户是否已登录
  const hasToken = getToken() // 获取token

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到首页
      next('/')
      NProgress.done() // 结束进度条
    } else {
      const hasGetUserInfo = store.getters.username
      if (!hasGetUserInfo) {
        await store.dispatch('user/getUserInfo')
      }

      next()
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // 只有前置守卫放行后，才会执行后置守卫
  // finish progress bar
  // console.dir(to)
  // console.dir(from)
  NProgress.done()
})
